package com.fms.data.messaging.data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.fms.model.domain.FlowSheet;
import com.fms.model.messaging.domain.IEmailData;

public class EmailDataFileFiller implements IEmailDataFiller
{

	private static final String	CONFIG_FILE	= "output.xml";
	private static final String	PACKAGE	= "com.fms.data.messaging.data";

	public void fill(IEmailData data)
	{
		EmailSettings settings = null;
		
		JAXBContext jc;
		try
		{
			jc = JAXBContext.newInstance(PACKAGE);
			Unmarshaller unmarshaller = jc.createUnmarshaller();
			settings = (EmailSettings)unmarshaller.unmarshal(new File(CONFIG_FILE));
			
			data.setFlowSheet(new FlowSheet(settings.getFlowSheetFile()));
			data.setMessage(settings.getMessage());
			data.setSubject(settings.getSubject());
			for(String s : settings.getDestinations())
			{
				data.addDestination(s);
			}


		}
		catch (JAXBException e)
		{
			e.printStackTrace();
			throw new RuntimeException("Error during XML processing.");
		} 

	}

	public void save(IEmailData data)
	{
		


		EmailSettings settings = new EmailSettings();
		settings.setFlowSheetFile(data.getFlowSheet().getFileName());
		settings.setMessage(data.getMessage());
		settings.setSubject(data.getSubject());
		for(String s : data.getDestinations())
		{
			settings.getDestinations().add(s);
		}
		try
		{
			JAXBContext jaxbContext = JAXBContext.newInstance(PACKAGE);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
					   new Boolean(true));
			marshaller.marshal(settings,
					   new FileOutputStream(CONFIG_FILE));

		} 
		catch (JAXBException e)
		{
			e.printStackTrace();
			throw new RuntimeException("Error during XML processing.");
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
			throw new RuntimeException("Unable to find configuration file.");
		}

	}

}
